package com.dynamic.datasource.transaction;

import com.dynamic.datasource.connection.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @author 王先堂
 * @Description 事务工具类
 * @createTime 2022/03/28/ 15:52:00
 */
@Slf4j
public class TransactionUtil {

    /**
     * 开启事务
     */
    public static void start() {
        String oldId = TransactionContext.get();
        if (StringUtils.isEmpty(oldId)) {
            String id = UUID.randomUUID().toString();
            TransactionContext.add(id);
            log.debug("start transaction local id {}", id);
        } else {
            log.debug("already started transaction local id {}", oldId);
        }
    }

    /**
     * 提交事务
     */
    public static void commit() {
        ConnectionFactory.notify(true);
        log.debug("commit transaction local id {}", TransactionContext.get());
        TransactionContext.remove();
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        ConnectionFactory.notify(false);
        log.debug("rollback transaction local id {}", TransactionContext.get());
        TransactionContext.remove();
    }
}
